package calao.plan.client;

import java.util.Vector;

import com.google.gwt.user.client.ui.Widget;

import calao.client.Desktop;
import calao.client.i18n.Text;
import calao.client.ui.DayTimeBox;
import calao.client.ui.EditableGrid;
import calao.client.ui.WeekDayBox;
import calao.client.util.DayTime;

public class WorkPeriodEditor
extends EditableGrid
{

	public static final int WEEKDAY_COL = 0;
	public static final int START_HOUR_COL = 1;
	public static final int END_HOUR_COL = 2;
	
	// cell editors
	final WeekDayBox weekDayBox = new WeekDayBox();
	final DayTimeBox startBox = new DayTimeBox();
	final DayTimeBox endBox = new DayTimeBox();
	
	final Text text = Desktop.getDesktop().text;
	
	public WorkPeriodEditor() 
	{
		super(3);
		setHeader(WEEKDAY_COL, text.day());
		setHeader(START_HOUR_COL, text.doStart());
		setHeader(END_HOUR_COL, text.end());
	}

	Vector list = new Vector();
	
	protected Widget getCellEditor(int row, int col) 
	{
		WorkPeriod period = getPeriod(row);
		switch (col) {
		case WEEKDAY_COL:
			weekDayBox.setWeekDay(period.getWeekDay());
			return weekDayBox;
		case START_HOUR_COL:
			startBox.setTime(period.startHour, period.startMin);
			return startBox;
		case END_HOUR_COL:
			endBox.setTime(period.endHour, period.endMin);
			return endBox;
		}
		return null;
	}

	protected Object getData(int row, int col) 
	{
		WorkPeriod period = getPeriod(row);
		switch (col) {
		case WEEKDAY_COL:
			return weekDayBox.getWeekDayText(period.getWeekDay());
		case START_HOUR_COL:
			return new DayTime(period.startHour, period.startMin);
		case END_HOUR_COL:
			return new DayTime(period.endHour, period.endMin);
		}
		return null;
	}

	protected int getRowCount() 
	{
		return list.size();
	}
	
	WorkPeriod getPeriod(int index)
	{
		return (WorkPeriod)list.get(index);
	}
	
	public WorkPeriod[] getWorkPeriods()
	{
		return (WorkPeriod[])list.toArray(new WorkPeriod[list.size()]);
	}
	
	public void setWorkPeriods(WorkPeriod[] periods)
	{
		list.clear();
		for (int i=0; i<periods.length; i++) {
			list.add(new WorkPeriod(periods[i]));
		}
	}

	protected void setData(int row, int col) 
	{
		WorkPeriod period = getPeriod(row);
		switch (col) {
		case WEEKDAY_COL:
			period.setWeekDay(weekDayBox.getWeekDay());
			break;
		case START_HOUR_COL:
			DayTime start = startBox.getTime();
			period.setStartHour(start.getHours());
			period.setStartMin(start.getMinutes());
			break;
		case END_HOUR_COL:
			DayTime end = endBox.getTime();
			period.setEndHour(end.getHours());
			period.setEndMin(end.getMinutes());
			break;
		}
	}

	protected void addRow() 
	{
		list.add(new WorkPeriod());
	}
	
	protected void removeRow(int row)
	{
		list.remove(row);
	}
	
	protected boolean canAddRow()
	{
		return true;
	}

	protected boolean canRemoveRow(int row)
	{
		return true;
	}

}
